package com.mengwen.backstage.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mengwen.backstage.service.RankService;
import lombok.extern.slf4j.Slf4j;


import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author LiangYonghui
 * @date 2020/4/20 23:44
 * @description 排行榜服务接口实现类
 */
@Service
@Slf4j
public class RankServiceImpl implements RankService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;





    @Override
    public Long batchAdd(String keyName, Map<String, Double> map) {
        Set<ZSetOperations.TypedTuple<String>> tuples = new HashSet<>();
        Set entrySet = map.entrySet();
        Iterator it = entrySet.iterator();
        while(it.hasNext()){
            Map.Entry me = (Map.Entry) it.next();
            String unionid = (String) me.getKey();
            double money = (double) me.getValue();
            log.info("unionid:" + unionid + " money:" + money);
            DefaultTypedTuple<String> tuple = new DefaultTypedTuple<>(unionid, money);
            tuples.add(tuple);
        }

        return  stringRedisTemplate.opsForZSet().add(keyName,tuples);

    }

    @Override
    public Boolean add(String keyName, String unionid, double money) {
        return stringRedisTemplate.opsForZSet().add(keyName, unionid, money);

    }

    @Override
    public Set<ZSetOperations.TypedTuple<String>> listRank(String keyName, int start, int end) {
        Set<String> range = stringRedisTemplate.opsForZSet().reverseRange(keyName, start, end);
        log.info("获取到的排行列表:");

        System.out.println("获取到的排行列表:" + (range.toString()));
        Set<ZSetOperations.TypedTuple<String>> rangeWithScores = stringRedisTemplate.opsForZSet().reverseRangeWithScores(keyName, start, end);
        System.out.println("获取到的排行和分数列表:" + rangeWithScores);
//        System.out.println("获取到的排行和分数列表:" + JSONUtils.toJSONString(rangeWithScores));
        return rangeWithScores;
    }

    @Override
    public double incrementMoney(String keyName, String unionid, double money) {
        Double score = stringRedisTemplate.opsForZSet().incrementScore(keyName, unionid, money);
        log.info(unionid + "+"+money +"元后：" + score);
        return score;
    }
}
